package jp.ac.utokyo.pinyomi;

import java.util.ArrayList;

public class Pair {

	/** The key */
	private ArrayList<String> key = new ArrayList<String>();
	
	/** The weight associated to the key . */
	private ArrayList<Double> val = new ArrayList<Double>();

	/** Category of the tuple, only used when necessary */
	private ArrayList<String> tag = new ArrayList<String>();

	
	/** Add a (key, value) pair */
	public void addPair(String k, Double v) {
		if (key.indexOf(k) == -1) {
			key.add(k);
			val.add(v);
		}
	}

	/** Add a (key, value) pair */
	public void addPair(String k, double v) {
		addPair(k, new Double(v));
	}

	/** Add a (key, value) pair */
	public void addPair(String k, String v) {
		addPair(k, new Double(v));
	}

	/** Add the ArrayList of pair */
	public void addPair(ArrayList<String> kl, ArrayList<Double> vl){
		key = kl;
		val = vl;
	}

	/** Add a (key, value, tag) triple */
	public void addTriple(String k, Double v, String t) {
		if (key.indexOf(k) == -1) {
			key.add(k);
			val.add(v);
			tag.add(t);
		}
	}

	/** Add a (key, value, tag) triple */
	public void addTriple(String k, double v, String t) {
		addTriple(k, new Double(v), t);
	}


	/** add tiple of specified pair  */
	public void addTriple(Pair pair) {
		for (int i = 0; i < pair.size(); i++)
			addTriple(pair.getKey(i), pair.getVal(i), pair.getTag(i));
	}
		
	/** Do normalization on weight(val), so that it was converted 
	 * to a probability distribution
	 */
	public void normalize()
	{
		double sum = 0.0;
		for(Double v: val){
			sum += v.doubleValue();
		}
		
		for (int i=0; i< val.size(); i++){
			val.set(i, new Double(Math.log(val.get(i).doubleValue() / sum)));
		}
	}

	/** return the log-probability of specified key */
	public double getLogProb(String k) {
		int idx = key.indexOf(k);
		if (idx == -1)
			return Settings.nullLogProb;
		else 
			return val.get(idx).doubleValue();
	}


	/** return the probability of specified key */
	public double getProb(String k) {
		return Math.exp(getLogProb(k));
	}


	/** return the probability at position k */
	public double getProb(int k) {
		return Math.exp(getLogProb(k));
	}


	/** return the log-probability at position k */
	public double getLogProb(int k) {
		return val.get(k).doubleValue();
		
	}


	/** return the key at position k */
	public String getKey(int k){
		return key.get(k);
	}

	/** return the value at position k */
	public Double getVal(int k){
		return val.get(k);
	}

	/** return the tag at position k */
	public String getTag(int k){
		return tag.get(k);
	}

	/** return the size of ArrayList */
	public int size() {
		return key.size();
	}
	
	/** whether the ArrayList contain the key */
	public boolean haskey(String k){
		return (key.indexOf(k) != -1);
	}
	
}
